package com.fastjars.business.captcha;

import org.patchca.service.Captcha;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

/**
 * Servlet
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/06/12
 * @version 1.0.0
 */
public class CaptchaServlet extends HttpServlet implements Servlet {
    private Properties props = new Properties();
    private Config config;

    @Override
    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);

        ImageIO.setUseCache(false);

        Enumeration<?> initParams = conf.getInitParameterNames();
        while (initParams.hasMoreElements())
        {
            String key = (String) initParams.nextElement();
            String value = conf.getInitParameter(key);
            this.props.put(key, value);
        }

        this.config = new Config(this.props);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set to expire far in the past.
        resp.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        resp.setHeader("Pragma", "no-cache");

        // return a png
        resp.setContentType("image/png");

        CaptchaService captchaService = new CaptchaService(this.config);

        Captcha captcha = captchaService.getCaptcha();

        // create the text for the image
        String capText = captcha.getChallenge();

        // store the text in the session
        req.getSession().setAttribute(this.config.getSessionKey(), capText);

        // store the date in the session so that it can be compared
        // against to make sure someone hasn't taken too long to enter
        // their kaptcha
        req.getSession().setAttribute(this.config.getSessionDate(), new Date());

        ServletOutputStream out = resp.getOutputStream();

        ImageIO.write(captcha.getImage(),"png", out);
    }
}
